import { FunctionComponent, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import useStore from '../../zustandStore/index';
import { useRequest } from 'ahooks';
import { userInfoService } from '../../api/user';
import { Popover, message } from 'antd';
import styles from './UserInfo.module.scss';
import { removeStorage } from '../../utils/storage';
const UserInfo: FunctionComponent = () => {
  const { username, nicename, avatar } = useStore(state => state.userInfo);
  const token = useStore(state => state.token);
  const setUserInfo = useStore(state => state.setUserInfo);
  const reSetUserInfo = useStore(state => state.reSetUserInfo);
  const nav = useNavigate();
  const { runAsync } = useRequest(userInfoService, { manual: true });
  const hanlderLogout = () => {
    removeStorage('token');
    reSetUserInfo();
    message.success('成功退出登录！');
    nav('/login');
  };
  const content = (
    <div className={styles.popContent}>
      <p>设置</p>
      <p onClick={hanlderLogout}>退出登录</p>
    </div>
  );
  const UserInfo = (
    <Popover content={content}>
      <span style={{ color: '#fff', cursor: 'pointer' }}>{username}</span>
    </Popover>
  );
  useEffect(() => {
    if (token && !username) {
      runAsync().then(({ data }) => {
        setUserInfo({ ...data });
      });
    }
  }, [token]);
  return <>{token ? UserInfo : <Link to={'/login'}>登录</Link>}</>;
};

export default UserInfo;
